﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace WoChu.CF.BaseFrame.Util
{
    public class DllFactory
    {
        private static readonly string ASSEMBLY_PATH = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);

        #region Instance...
        private static object _Object = new object();
        private static DllFactory _Instance;

        protected DllFactory() { }

        /// <summary>
        /// Instance
        /// </summary>
        public static DllFactory Instance
        {
            get
            {
                if (_Instance == null)
                {
                    lock (_Object)
                    {
                        if (_Instance == null)
                            _Instance = new DllFactory();
                    }
                }
                return _Instance;
            }
        }
        #endregion Instance...


        /// <summary>
        /// 通过反射实例化一个对象
        /// </summary>
        /// <param name="pName">类的名称</param>
        /// <param name="pPars">加载类需要的参数描述信息</param>
        /// <param name="pAssemblyName">对应配件的名称</param>
        /// <returns></returns>
        public object LoadObject(string objName, string objAssemblyName)
        {
            string filePath = ASSEMBLY_PATH + "\\" + objAssemblyName;
            object obj = null;
            if (System.IO.File.Exists(filePath))
            {
                Assembly DLL = Assembly.LoadFrom(filePath);
                System.Type t = DLL.GetType();

                obj = DLL.CreateInstance(objName);
            }
            else
            {
                TraceEx.Write("加载对象" + objName + "出错！请检查:" + filePath + " 是否存在！", SysMessageLevel.SysErrInfo);
            }
            TraceEx.WriteIf(obj != null, "加载对象" + objName + "出错！", SysMessageLevel.SysErrInfo);
            return obj;
        }
    }
}
